package com.itheima.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson2.JSON;
import com.itheima.common.Code;
import com.itheima.common.Result;
import com.itheima.common.ThreadLocalUtil;
import com.itheima.common.ValidateCodeUtils;
import com.itheima.dto.UserlogInDto;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import com.itheima.vo.UserlogInVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("user")
@Slf4j
public class UserController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    @PostMapping("login")
    public Result login(@RequestBody UserlogInDto userlogInDto){
        Object o = redisTemplate.opsForValue().get("msg" + userlogInDto.getPhone());
        if(o==null||!o.toString().equals(userlogInDto.getCode())){
            return Result.error(Code.Forbidden.getCode());
        }
        UserlogInVo userlogInVo = userService.login(userlogInDto);
        BeanUtils.copyProperties(userlogInVo,userlogInDto);
        userlogInDto.setToken(null);
        redisTemplate.opsForValue().set("user_token:"+userlogInVo.getToken(), JSON.toJSONString(userlogInDto),30,TimeUnit.MINUTES);
        return Result.success(userlogInVo);

    }


    @PostMapping("loginout")
    public Result loginout(HttpServletRequest request){
        String token = request.getHeader("AuthorizationUser");
        Object o = redisTemplate.opsForValue().get("user_token:" + token);
        UserlogInDto userlogInDto = JSON.parseObject(o.toString(), UserlogInDto.class);
        Boolean delete = redisTemplate.delete("user_token:" + token);
        Boolean loginout=userService.loginout(userlogInDto);
        if (delete&&loginout){
            return Result.success();
        }
        return Result.error(Code.Forbidden.getCode());
    }

    @PostMapping("sendMsg")
    public Result sendMsg(@RequestBody UserlogInDto userlogInDto){
        String s = ValidateCodeUtils.generateValidateCode4String(6);
        log.info("验证码发送成功：{}",s);
        redisTemplate.opsForValue().set("msg"+userlogInDto.getPhone(),s,60, TimeUnit.SECONDS);
        return Result.success(null,"手机验证码发送成功");
    }

}

